import os

from dotenv import load_dotenv
from sqlalchemy.orm import Session
from sqlalchemy import select
from fastapi import HTTPException
from ..models.videos_model import Videos
from ..utils.uploads_oss import main as upload_on_oss

load_dotenv()
SOURCES_PATH=os.getenv("SOURCES_PATH")

def get_video_by_id(db: Session, video_id: int):
    try:
        query = (
            db.query(Videos)
            .filter(Videos.id == video_id)
        )

        # 执行查询并转换为字典列表
        results = [video.as_dict() for video in query.all()]

        return results

    finally:
        db.close()

def create_video(db: Session, name: str, path: str, type: int = 1):
    # 检查 name 是否已存在
    existing_video = db.query(Videos).filter(Videos.name == name).first()
    if existing_video:
        raise HTTPException(status_code=400, detail=f"视频名称 '{name}' 已存在")
    file_path=os.path.join(SOURCES_PATH, path)
    # upload_on_oss(file_path=file_path, key=path)
    db_video = Videos(name=name, path=path, type=type,
                      oss_url="http://whatteam1.oss-cn-beijing.aliyuncs.com/"+path)
    db.add(db_video)
    db.commit()
    db.refresh(db_video)
    return db_video.as_dict()


def update_video_by_id(db: Session, video_id: int, name: str, type: int):
    # 查询视频对象
    video = db.execute(select(Videos).where(Videos.id == video_id)).scalars().first()

    if not video:
        raise HTTPException(status_code=404, detail="视频不存在")

    # 更新字段
    if name is not None:
        video.name = name
    if type is not None:
        video.type = type

    # 提交事务
    db.commit()
    db.refresh(video)

    return video.as_dict()
def delete_video_by_id(db: Session, video_id: int):
    # 查询视频对象
    video = db.execute(select(Videos).where(Videos.id == video_id)).scalars().first()
    if not video:
        raise HTTPException(status_code=404, detail="视频不存在")

    # 执行删除操作
    db.delete(video)
    db.commit()

    return video.as_dict()


def update_oss_urls(db: Session):
    try:
        # 查询所有视频记录
        videos = db.query(Videos).all()

        # 遍历每个视频记录，更新 oss_url
        for video in videos:
            if video.path:  # 确保 path 不为空
                video.oss_url = f"http://whatteam1.oss-cn-beijing.aliyuncs.com/{video.path}"

        # 提交事务
        db.commit()

        return {"message": "OSS URLs updated successfully"}

    except Exception as e:
        db.rollback()  # 回滚事务
        raise HTTPException(status_code=500, detail=str(e))

# if __name__ == "__main__":
#     from database.db import SessionLocal
#     db = SessionLocal()
#     a=update_oss_urls(db)